//全局控制类

import AudioManager from "../Common/AudioManager";
import WXCtr from "./WXCtr";
import Http from "../Common/Http";
import UserManager from "../Common/UserManager";
import Start from "../View/start/Start";
import End from "../View/end/End";
import Revive from "../View/end/Revive";
import RankingView from "../View/ranking/RankingView";
import { Game } from "../View/game/Game";
import GameData from "../Common/GameData";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameCtr {
    public static ins: GameCtr;
    private mGame: Game;
    private mStart: Start;
    private mEnd: End;
    public mRanking: RankingView;
    private mRevive: Revive;

    public static shareSwitch = false;
    public static slideData = null;
    public static randomUserData = null;
    public static surplusReviveTimes = 0;               //剩余复活次数
    public static reviveTimes = 1;                      //第几次复活
    public static score: number = 0;
    public static exp: number = 0;
    public static rankingEntrance = "Start";            //排行榜界面入口，默认开始界面

    public static reviveData = null;
    public static gameOverSwitchsInfo = null;
    public static friendsCircleImg = "";                //分享到朋友圈图片地址
    public static gameReviveData = [];//游戏结束后  游戏中的数据保存
    public static videoAd = null;
    public static StartAd = null;
    public static GameConfig = null;    //获得游戏配置数据
    public static iSteaching = true;//教学
    public static selfGoldCount = 0;//金币的数量
    public static CashBase = null;//取配置和现金首页信
    public static isonceRad = false;//玩家 启动游戏第一次
    public static toolData = null;//道具列表
    public static isover = null;//游戏结束
    public static RoomId = null;
    public static PropsSwitch = "";
    public static AllPropList = null;
    public static fuhuobingNum = 100000;//复活币
    public static sliderData = null;//
    public static sliderDataGame = null;//
    public static DataGame = [];//

    public static GameUerinfo = null;
    constructor() {
        GameCtr.ins = this;
        // WXCtr.getLaunchOptionsSync();
      //  WXCtr.showShareMenu();
        // // WXCtr.createUserInfoBtn();
       // WXCtr.wxOnLogin();
        // WXCtr.getSelfData();

        // GameCtr.getRandomUser();
        // GameCtr.getGameConfig();
        // GameCtr.getPROPSSWITCH();
       // GameData.getAllGameData();
    }

    static getInstance() {
        if (!GameCtr.ins) {
            GameCtr.ins = new GameCtr();
        }
        return GameCtr.ins;
    }

    //获得游戏配置数据
    static getGameConfig() {
        Http.send({
            url: Http.UrlConfig.SPCIAL,
            success: (resp) => {
                console.log("获得游戏配置数据", resp);
                if (resp.code == 200) {
                    GameCtr.GameConfig = resp.data;//refresh_number
                }
            },
            error: (resp) => {

            }
        });
    }

    //获取配置和现金首页信息
    static getCashBase(callback = null) {
        Http.send({
            url: Http.UrlConfig.GETCASHBASE,
            data: {
                user_id: UserManager.user_id
            },
            success: (resp) => {
                console.log("获取配置和现金首页信息", resp);
                if (resp.code == 200) {
                    GameCtr.CashBase = resp.data;
                    if (callback != null) {
                        callback();
                    }
                }
            },
            error: (resp) => {

            }
        });
    }

    //道具开关
    static getPROPSSWITCH(callback = null) {
        Http.send({
            url: Http.UrlConfig.PROPSSWITCH,
            data: {
                user_id: UserManager.user_id
            },
            success: (resp) => {
                console.log("获取奖励道具开关", resp);
                if (resp.code == 200) {
                    GameCtr.PropsSwitch = resp.data.PropsSwitch;
                }
            },
            error: (resp) => {

            }
        });
    }

    //查询所有道具
    static getAllPropList(callback = null) {
        Http.send({
            url: Http.UrlConfig.AllPropList,
            success: (resp) => {
                console.log("获取奖励道具开关", resp);
                if (resp.code == 200) {
                    GameCtr.PropsSwitch = resp.data.PropsSwitch;
                }
            },
            error: (resp) => {

            }
        });
    }


    //提交提现
    static DoExchange(call = null) {
        Http.send({
            url: Http.UrlConfig.DOEXCHANGE,
            data: {
                user_id: UserManager.user_id
            },
            success: (resp) => {

                if (resp.code == 450) {
                    console.log("450未登陆", resp.data);
                }
                else if (resp.code == 471) {
                    console.log("471奖金不足1元，", resp.data);
                }
                else if (resp.code == 472) {
                    console.log("472超过10元，请联系客服兑换，", resp.data);
                }
                else if (resp.code == 473) {
                    console.log("473每天可以兑换3次，明天再来", resp.data);
                }
                else {
                    GameCtr.CashBase.money = 0;
                    if (call != null) {
                        call();
                    }
                    console.log("提交提现cg", resp.data);
                }

            },
            error: (resp) => {

            }
        });
    }

    //领取红包到余额里
    static sendGetRad(callback = null) {
        Http.send({
            url: Http.UrlConfig.DOSCORE,
            data: {
                user_id: UserManager.user_id,
                score: GameCtr.CashBase.scoreDay
            },
            success: (resp) => {
                if (resp.code == 450) {
                    console.log("450未登陆", resp.data);
                }
                else if (resp.code == 470) {
                    console.log("470未达到分数，", resp.data);
                }
                else if (resp.code == 471) {
                    console.log("471已瓜分完所有奖金，", resp.data);
                }
                else if (resp.code == 473) {
                    console.log("473每天可以兑换3次，明天再来", resp.data);
                }
                else {
                    GameCtr.CashBase.money = GameCtr.CashBase.money + resp.data.money;
                    if (callback != null) {
                        callback();
                    }
                    console.log("send", GameCtr.CashBase.money);
                    console.log("sendGetRad提交提现cg", resp.data);
                }
            },
            error: (resp) => {

            }
        });
    }

    //设置game实例(游戏)
    setGame(game: Game) {
        this.mGame = game;
    }
    //设置start实例（开始）
    setStart(start: Start) {
        this.mStart = start;
    }
    //设置end实例（结束）
    setEnd(end: End) {
        this.mEnd = end;
    }
    //设置ranking实例（排行）
    setRanking(ranking: RankingView) {
        this.mRanking = ranking;
    }
    //设置revive实例（复活）
    setRevive(revive: Revive) {
        this.mRevive = revive;
    }

    //场景切换
    static gotoScene(sceneName) {
        cc.director.loadScene(sceneName);
    }

    //获取分享开关（此处的开关特指开始界面分享按钮上的“分享有礼”）
    static getShareSwitch() {
        Http.send({
            url: Http.UrlConfig.SHARE_SWITCH,
            success: (resp) => {
                GameCtr.ins.mStart.ndShareTip.active = GameCtr.shareSwitch = resp.data;
            },

        });
    }

    //显示结束界面
    static showEnd() {
        GameCtr.gotoScene("End");
    }

    //显示开始界面
    static showStart() {
        GameCtr.gotoScene("Start");
    }

    //显示复活界面
    static showRevive(isShow: boolean) {
        if (GameCtr.ins) {
            GameCtr.ins.mRevive.ndRevive.active = isShow;
            if (isShow) {
                GameCtr.ins.mRevive.showScore(GameCtr.score);
            }
        }
    }

    //开始游戏
    static startGame() {
        GameCtr.reviveTimes = 1;
        if (GameCtr.reviveData) {
            GameCtr.surplusReviveTimes = GameCtr.reviveData.revive_number;
        }
        GameCtr.gotoScene("fkxxl");
    }

    //显示排行榜
    static showRanking(entrance) {
        GameCtr.rankingEntrance = entrance;
        GameCtr.gotoScene("Ranking");
    }

    //复活继续游戏
    static revive() {
        GameCtr.surplusReviveTimes--;
        GameCtr.gotoScene("fkxxl");
    }


    //播放背景音乐
    static playBgm() {
        // AudioManager.getInstance().playMusic("audio/bgm", true, 1); 
    }

    //增加分数
    static addScore(num) {
        if (GameCtr.ins) {
            GameCtr.score += num;
            // GameCtr.checkOther(GameCtr.score);
            GameCtr.ins.mGame.setScore();
        }
    }

    //清除分数
    static deleteScore() {
        if (GameCtr.ins) {
            GameCtr.score = 0;
            //GameCtr.checkOther(GameCtr.score);
            GameCtr.addScore(GameCtr.score);
        }
    }

    //游戏结束
    static gameOver() {
        if (GameCtr.ins) {
            WXCtr.submitScoreToWx(GameCtr.score);
            GameCtr.sendScore();
            GameCtr.gotoScene("End");
        }
    }

    //复活文字提示
    static reviveTip(tipString = null) {
        GameCtr.ins.mRevive.showShareGroupTip(tipString);
    }

    //发送分数到游戏服务器
    static sendScore() {
        // Http.send({
        //     url: Http.UrlConfig.SEND_SCROE,
        //     success: (resp) => {
        //         if (resp.data.circle_image) {
        //             GameCtr.friendsCircleImg = resp.data.circle_image;
        //         }
        //     },
        //     data: {
        //         user_id: UserManager.user_id,
        //         score: GameCtr.score
        //     }
        // });
    }

    //登录游戏
    static login(code, info, showWorldRanking = false) {
        Http.send({
            url: Http.UrlConfig.LOGIN,
            success: (resp) => {
                if (resp.status == Http.Code.OK) {
                    console.log("登陆失败登陆失败登陆失败登陆失败登陆失败", WXCtr.launchOption.query);
                    console.log("openidopenidopenidopenidopenid", resp.data);
                    console.log("openidopenidopenidopenidopenid", resp.data.openid);
                    resp.data = JSON.parse(resp.data);
                    UserManager.user_id = resp.data.openid;
                    let datasocr = JSON.stringify(GameData.score);
                    console.log("openidopenidopenidopenidopenid", UserManager.user_id);
                    // GameCtr.getCashBase();
                    if (showWorldRanking) {
                        //GameCtr.ins.mRanking.showWorldRanking();
                    }
                    //  GameCtr.ttttttt();
                    Http.send({
                        url: Http.UrlConfig.SAVE_INFO,
                        data:
                            {
                                avatar_url: info.avatarUrl,
                                city: info.city,
                                country: info.country,
                                gender: info.gender,
                                language: info.language,
                                nick_name: info.nickName,
                                openid: UserManager.user_id,
                                province: info.province,
                                datas: datasocr
                            },
                        success: () => {
                            // GameCtr.getShareSwitch(); //登录成功，获取分享开关
                            // GameCtr.getRandomUser();
                            // GameCtr.getGameOverShareSwitch();
                            console.log("渠道验证成功111", WXCtr.launchOption.query);

                            GameCtr.chanelCheck(WXCtr.launchOption.query.channel_id, UserManager.user_id);
                            //GameCtr.ttttttt();
                            // GameCtr.seekJion(WXCtr.launchOption.query.Send_user_id, WXCtr.launchOption.query.isInvite);
                            // WXCtr.getAdConfig();
                            // GameCtr.getUserInfoCtr();
                        },
                        error: () => {
                            console.log("登陆失败", WXCtr.launchOption.query);
                        }
                    });
                }
            },
            data: {
                code: code
            }
        });

    }

    //获取广告配置
    static getSliderAndMoreGameKAIGUAN(slideType) {
        Http.send({
            url: Http.UrlConfig.GET_KAIGUAN,
            success: (resp) => {
                GameCtr.ins.mStart.showSlideKAIGUAN(resp, slideType);

                console.log("getSliderAndMoreGameKAIGUAN", resp);
                //GameCtr.ins.mStart.showSlide(resp.data);

            },
            data: {
                zdid: slideType
            }
        });
    }

    //获取广告配置
    static getSliderConfig(slideType) {
        Http.send({
            url: Http.UrlConfig.GET_ADSCONFIG,
            success: (resp) => {
                if (resp.status) {
                    console.log("getSlider数据", resp);
                    if (slideType == "184") {
                        GameCtr.ins.mStart.showSlide(resp.data);
                        console.log("184184184", resp);
                    } else if (slideType == "185") {
                        GameCtr.ins.mStart.showmoreGaem(resp.data);
                        console.log("185185", resp);
                    }
                }
            },
            data: {
                zdid: slideType
            }
        });
    }

    //获取随机超越数据
    static getRandomUser() {
        Http.send({
            url: Http.UrlConfig.GET_RANDOMUSER,
            success: (resp) => {
                console.log("get randomUserData数据", resp);
                GameCtr.randomUserData = resp.data;
                console.log("get randomUserData数据", GameCtr.randomUserData);
            },
            data: {
                limit: 10
            }
        });
    }

    //超越好友检查
    static checkOther(score) {
        if (!GameCtr.randomUserData) return;
        console.log("checkOther", GameCtr.randomUserData);
        if (GameCtr.score > 60) {
            for (let i = 0; i < GameCtr.randomUserData.length; i++) {
                let data = GameCtr.randomUserData[i];
                if (score > data.highest_score) {
                    console.log("checkOther", score);
                    GameCtr.ins.mGame.showOther(data.avatar);
                    GameCtr.randomUserData.splice(i, 1);
                    return;
                }
            }
        }
    }

    //渠道验证
    static chanelCheck(chanelId, userId) {
        Http.send({
            url: Http.UrlConfig.CHANEL_RECORD,
            data: {
                user_id: userId,
                channel_id: chanelId
            },
            success: (resp) => {
                console.log("渠道验证成功", resp);
            }
        });
    }

    //渠道验证
    static ttttttt() {
        // GameCtr.ins.mStart.showttttt();
    }

    static daliySignin() {
        // Http.send({
        //     url: Http.UrlConfig.SINGNI,
        //     data: {
        //         openid: UserManager.user_id,
        //     },
        //     // success: (resp) => {
        //     //     let qiandaotian = GameData.qiandao;
        //     //     GameData.qiandao = qiandaotian + 1;
        //     //     GameCtr.ins.mStart.setqiandao(true);
        //     // },
        //     // error: (resp) => {
        //     //     GameCtr.ins.mStart.setqiandao(false);
        //     // }
        // });
    }

    //好友求助进入游戏    WXCtr.launchOption.query.
    static seekJion(Send_user_id, isInvite) {
        console.log("seekJionseekJionseekJionseekJion", isInvite);
        if (Send_user_id == null || Send_user_id == undefined || Send_user_id == "") {
            return;
        }
        if (isInvite == "true" && isInvite !== "" && isInvite != undefined && isInvite != null) {
            console.log("111111111111111111111111111111111111111111", isInvite);
            Http.send({
                url: Http.UrlConfig.INVITE,
                data: {
                    user_id: UserManager.user_id,
                    friend_user_id: Send_user_id
                },
                success: (resp) => {
                    console.log("邀请进入游戏", resp.data.m);
                    //GameCtr.ins.mStart.showGetTool(resp.data.m);
                    console.log("邀请进入游戏", resp);
                }
            });
        }
        else {
            console.log("2222222222222222222222222222222222222222222", isInvite);
            Http.send({
                url: Http.UrlConfig.DODAOJU,
                data: {
                    user_id: UserManager.user_id,
                    ToUser_id: Send_user_id
                },
                success: (resp) => {
                    console.log("好友求助进入游戏", resp.data.m);
                    GameCtr.ins.mStart.showGetTool(resp.data.m);
                    console.log("好友求助进入游戏", resp);
                }
            });
        }
    }

    //个人道具列表
    static getToolInfo() {
        Http.send({
            url: Http.UrlConfig.GETDAOJU,
            data: {
                user_id: UserManager.user_id,
            },
            success: (resp) => {
                GameCtr.toolData = resp.data;
                // GameCtr.ins.mStart.showSeekGetTool(resp.data.new);
                console.log("个人道具列表", resp.data);
            }
        });
    }

    //在游戏里面个人道具列表
    static getGameToolInfo() {
        Http.send({
            url: Http.UrlConfig.GETDAOJU,
            data: {
                user_id: UserManager.user_id,
            },
            success: (resp) => {
                GameCtr.toolData = resp.data;
                GameCtr.ins.mGame.showSeekGetTool(resp.data.new, resp.data.data);
                console.log("在游戏里面getGameToolInfo", resp);
            }
        });
    }

    static addToolByTypeCtr(type) {
        GameCtr.ins.mGame.addToolByType(type);
    }

    //个人道具列表
    static getToolInfoOnce(callback: Function = null) {
        Http.send({
            url: Http.UrlConfig.GETDAOJU,
            data: {
                user_id: UserManager.user_id,
            },
            success: (resp) => {
                GameCtr.toolData = resp.data;
                if (callback != null) {
                    callback();
                }
                console.log("个人道具列表", resp);
            }
        });
    }

    static getInviteFriend(callback: Function = null) {
        Http.send({
            url: Http.UrlConfig.RESULT,
            data: {
                user_id: UserManager.user_id
            },
            success: (resp) => {
                if (callback != null) {
                    callback(resp.data);
                }
                console.log("邀请好友求列表", resp.data);
            },
            error: (resp) => {
                console.log("邀请好友求列表失败", resp.data);
            }
        });
    }

    //消耗
    static SendConsume(toolid = 1, callback: Function = null) {
        // Http.send({
        //     url: Http.UrlConfig.DELDAOJU,
        //     data: {
        //         user_id: UserManager.user_id,
        //         prop_id: toolid
        //     },
        //     success: (resp) => {
        //         if (callback != null) {
        //             callback();
        //         }
        //         console.log("消耗个人道具", resp);
        //     }
        // });
    }

    //分享到群检测
    static shareGroupCheck(encryptedData, iv) {
        Http.send({
            url: Http.UrlConfig.SHARE_GROUP,
            data: {
                user_id: UserManager.user_id,
                encrypted_data: encryptedData,
                iv: iv
            },
            success: (resp) => {
                console.log("分享到群成功", resp);
                if (resp.code == 200) {
                    GameCtr.getGold("group");
                } else if (resp.code == 403) {
                    GameCtr.reviveTip("今天已经分享过这个了！");
                }
            }
        });
    }

    //获取复活配置
    static getReviveData() {
        Http.send({
            url: Http.UrlConfig.REVIVE_DATA,
            success: (resp) => {
                console.log("获取复活配置信息", resp);
                GameCtr.reviveData = resp.data;
            }
        });
    }

    //获取复活界面所有开关
    static getGameOverShareSwitch() {
        Http.send({
            url: Http.UrlConfig.GAMEOVER_SHARESWITCH,
            success: (resp) => {
                console.log("获取复活界面所有开关信息", resp);
                GameCtr.gameOverSwitchsInfo = resp.data;
            },
            data: {
                user_id: UserManager.user_id
            }
        });
    }

    static getFriendsCircleGold() {
        setTimeout(() => { GameCtr.getGold("circle"); }, 30000);
    }

    //获取金币
    static getGold(method) {
        console.log("获取金币, method = ", method);
        console.log("获取金币, User_id = ", UserManager.user_id);
        Http.send({
            url: Http.UrlConfig.GET_GOLD,
            success: (resp) => {
                console.log("获取金币成功", resp);
                GameCtr.ins.mRevive.getUserInfo();
            },
            data: {
                user_id: UserManager.user_id,
                method: method
            }
        });
    }

    //根据图片路径设置sprite的spriteFrame
    static loadImg(spr, imgUrl) {
        if (imgUrl == null || imgUrl == "")
            return;
        cc.loader.load({
            url: imgUrl,
            type: 'png'
        }, (err, texture) => {
            console.log("loadImgloadImg", err);
            spr.spriteFrame = new cc.SpriteFrame(texture);
        });
    }

    //裁剪字符串，超出指定长度之后显示...(每个中文字符长度为2）
    static cutstr(str, len) {
        let str_length = 0;
        let str_len = 0;
        let str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            let a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length > len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        // //如果给定字符串小于指定长度，则返回源字符串； 
        // if (str_length < len) {
        //     return str;
        // }
        return str;
    }

    static setResurgence(NUM) {
        //  GameCtr.ins.mGame.setResurgence(NUM);
    }

    static ReviveGameSettingCtr() {
        GameCtr.ins.mGame.ReviveGameSetting();
    }

    static teachingCtr() {
        GameCtr.ins.mGame.teaching();
    }

    static colseteachingCtr() {
        GameCtr.ins.mGame.colseteaching();
    }

    static getUserInfoCtr() {
        Http.send({
            url: Http.UrlConfig.GET_USERINFO,
            success: (resp) => {
                console.log("get self UserInfo response == ", resp);
                GameCtr.selfGoldCount = resp.data.gold_amount;
            },
            data: {
                user_id: UserManager.user_id
            }
        });
    }



    static BuyTool(toolid, callback: Function = null) {
        // Http.send({
        //     url: Http.UrlConfig.BUY_TOOL,
        //     success: (resp) => {
        //         console.log("BuyTool", resp);
        //         GameCtr.addToolByTypeCtr(resp.data.m);
        //         GameCtr.selfGoldCount = GameCtr.selfGoldCount - resp.data.amount;
        //         GameCtr.ins.mGame.buyTip(true);
        //     },
        //     error: (resp) => {
        //         console.log("BuyTool", resp);
        //         GameCtr.ins.mGame.buyTip(false);
        //     },
        //     data: {
        //         user_id: UserManager.user_id,
        //         table: GameCtr.RoomId,
        //         daoju_id: toolid
        //     }
        // });
    }

    static createImage(avatarUrl, sprHead: cc.Sprite) {
        if (window.wx != undefined) {
            try {
                let image = wx.createImage();
                image.onload = () => {
                    try {
                        let texture = new cc.Texture2D();
                        texture.initWithElement(image);
                        texture.handleLoadedTexture();
                        sprHead.spriteFrame = new cc.SpriteFrame(texture);
                    } catch (e) {
                        cc.log(e);
                        sprHead.node.active = false;
                    }
                };
                image.src = avatarUrl;
            } catch (e) {
                cc.log(e);
                sprHead.node.active = false;
            }
        } else {
            cc.loader.load({
                url: avatarUrl,
                type: 'jpg'
            }, (err, texture) => {
                sprHead.spriteFrame = new cc.SpriteFrame(texture);
            });
        }
    }


}
